package com.example.basicdemo.controller;


import com.alibaba.fastjson.JSONObject;
import com.example.basicdemo.dao.mapper.RpcConnectMapper;
import com.example.basicdemo.model.DemoBaseResult;
import com.example.basicdemo.model.builder.*;
import com.example.basicdemo.model.domain.*;
import com.example.basicdemo.model.result.*;
import com.example.basicdemo.service.PermissionService;
import com.isyscore.os.config.client.annotation.IscValue;
import com.isyscore.os.dev.api.dmc.model.builder.*;
import com.isyscore.os.dev.api.dmc.model.domain.DataTypeBOOL;
import com.isyscore.os.dev.api.dmc.model.domain.TslDetailDomain;
import com.isyscore.os.dev.api.dmc.model.domain.TslItemDomain;
import com.isyscore.os.dev.api.dmc.model.enums.*;
import com.isyscore.os.dev.api.dmc.model.result.*;
import com.isyscore.os.dev.api.dmc.service.DmcService;
import com.isyscore.os.dev.config.IsyscoreConfigProperties;
import com.isyscore.os.dev.config.IsyscoreConstants;
import com.isyscore.os.dev.util.IsyscoreHashMap;
import com.isyscore.os.dev.util.TokenUtils;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/${api-module}/demo")
public class DemoController {

    @Autowired
    private PermissionService permissionService;
    @Autowired
    private DmcService dmcService;

    /**
     * 创建角色
     * 创建用户
     * 用户登录
     * 获取用户信息
     * 获取功能权限菜单
     */
    @GetMapping("creatRole")
    public DemoBaseResult creatRole() {
        SaveRoleAclRequestBuilder builder = new SaveRoleAclRequestBuilder();
        RoleParamDomain param = new RoleParamDomain();
        param.setName("测试角色" + new Random().nextInt(Short.MAX_VALUE + 1));
        param.setAuthorizedAcls(Arrays.asList());
        param.setAuthorizedApps(Arrays.asList("device-manage"));
        param.setRemark("创建测试角色");
        JSONObject roleExtKeyVal = new JSONObject();
        roleExtKeyVal.put("key", "value");
        param.setRoleExtKeyVal(roleExtKeyVal);
        builder.setBizModel(param);
        SaveRoleAclResult result = permissionService.saveRoleAcl(builder);
        JSONObject resultJson = JSONObject.parseObject(JSONObject.toJSONString(result));
        resultJson.put("message", "您已成功创建一个角色, 其名称为: " + param.getName() + ", 您可以前往<权限管理>应用中的<角色管理>模块确认");
        DemoBaseResult.Data data = new DemoBaseResult.Data()
                .setParam(JSONObject.parseObject(JSONObject.toJSONString(param)))
                .setResult(resultJson);
        return new DemoBaseResult().setData(data);
    }

    private static String loginName = "";
    private static String password = "";

    @GetMapping("creatUser")
    public DemoBaseResult creatUser() {
        SaveUserRequestBuilder builder = new SaveUserRequestBuilder();
        SysUserLDAPDomain param = new SysUserLDAPDomain();
        param.setNickname("测试用户" + new Random().nextInt(Short.MAX_VALUE + 1));
        param.setLoginName("loginNameTest" + new Random().nextInt(Short.MAX_VALUE + 1));
        param.setStatus("ENABLE");
        param.setAuthIdList(Arrays.asList());
        param.setRoleIdList(Arrays.asList("1"));
        param.setRentalList(Arrays.asList("1"));
        param.setPassword("password" + new Random().nextInt(Short.MAX_VALUE + 1) + "");
        param.setPhone("18888888881");
        param.setPicture("");
        param.setUserType("业务类型");
        JSONObject colKeyVal = new JSONObject();
        colKeyVal.put("key", "value");
        param.setColKeyVal(colKeyVal);
        builder.setBizModel(param);
        SaveUserResult result = permissionService.saveUser(builder);
        JSONObject resultJson = JSONObject.parseObject(JSONObject.toJSONString(result));
        resultJson.put("message", "您已成功创建一个用户, 其名称为: " + param.getNickname() + ", 您可以前往<权限管理>应用中的<用户管理>模块确认");
        DemoBaseResult.Data data = new DemoBaseResult.Data()
                .setParam(JSONObject.parseObject(JSONObject.toJSONString(param)))
                .setResult(resultJson);
        loginName = param.getLoginName();
        password = param.getPassword();
        return new DemoBaseResult().setData(data);
    }

    private static String token = "";
    private static String userId = "";

    @GetMapping("login")
    public DemoBaseResult login() {
        OsLoginRequestBuilder builder = new OsLoginRequestBuilder();
        builder.setLoginName(loginName);
        builder.setPassword(password);
        OsLoginResult result = permissionService.osLogin(builder);
        JSONObject resultJson = JSONObject.parseObject(JSONObject.toJSONString(result));
        resultJson.put("message", "您已成功登录用户, 其名称为: " + builder.getLoginName());
        DemoBaseResult.Data data = new DemoBaseResult.Data()
                .setParam(JSONObject.parseObject(builder.toJsonString()))
                .setResult(resultJson);
        LoginInfoDomain loginInfo = result.parseData();
        if (loginInfo!=null){
            token = loginInfo.getToken();
            userId = loginInfo.getUserId();
        }
        return new DemoBaseResult().setData(data);
    }

    @GetMapping("getUserInfo")
    public DemoBaseResult getUserInfo() {
        OsLoginStatusRequestBuilder builder = new OsLoginStatusRequestBuilder();
        IsyscoreHashMap header = new IsyscoreHashMap();
        header.put("token", token);
        builder.setHeaders(header);
        OsLoginStatusResult result = permissionService.osLoginStatus(builder);
        JSONObject resultJson = JSONObject.parseObject(JSONObject.toJSONString(result));
        resultJson.put("message", "您已成功获取上次操作登录的用户, 其token为: " + token);
        DemoBaseResult.Data data = new DemoBaseResult.Data()
                .setParam(JSONObject.parseObject(builder.toJsonString()))
                .setResult(resultJson);
        return new DemoBaseResult().setData(data);
    }

    @GetMapping("getAclList")
    public DemoBaseResult getAclList() {
        QueryUserAclRequestBuilder builder = new QueryUserAclRequestBuilder();
        IsyscoreHashMap header = new IsyscoreHashMap();
        header.put("token", token);
        builder.setHeaders(header);
        builder.setAppCode("device-manage");
        QueryUserAclResult result = permissionService.queryUserAcl(builder);
        JSONObject resultJson = JSONObject.parseObject(JSONObject.toJSONString(result));
        resultJson.put("message", "您已成功获取上次操作登录的用户的设备集成权限, 其token为: " + token);
        DemoBaseResult.Data data = new DemoBaseResult.Data()
                .setParam(JSONObject.parseObject(builder.toJsonString()))
                .setResult(resultJson);
        return new DemoBaseResult().setData(data);
    }


    /**
     * 创建设备类
     * 创建设备
     * 修改设备属性
     * 获取设备详情
     * 查询设备属性
     */
    @GetMapping("addProduct")
    public DemoBaseResult addProduct() {
        AddProductRequestBuilder builder = new AddProductRequestBuilder();
        builder.setHeaders(new IsyscoreHashMap());
        builder.setAuthType(AuthenticationEnum.DEVICE_CORRESPONDS_TO_SECRET);
        builder.setCommunicationType(ProtocolEnum.MQTT);
        builder.setConnectType(ConnectTypeEnum.SUB_DEVICE);
        builder.setGroupId("group0");
        builder.setNetworkingType(NetworkingTypeEnum.ETHERNET);
        builder.setProductKey("CM4GNAc08WC");
        builder.setProductName("设备类" + new Random().nextInt(Short.MAX_VALUE + 1));
        builder.setProtocol(0);
        AddProductResult result = dmcService.addProduct(builder);
        JSONObject resultJson = JSONObject.parseObject(JSONObject.toJSONString(result));
        resultJson.put("message", "您已成功创建设备类, 其名称为: " + builder.getProductName() + ", 您可以前往设备集成-设备管理-设备类查看该设备类");
        DemoBaseResult.Data data = new DemoBaseResult.Data()
                .setParam(JSONObject.parseObject(JSONObject.toJSONString(result.getResponse().getParamMap())))
                .setResult(resultJson);

        //同时创建设备模型
        AddDeviceModelRequestBuilder modelBuilder = new AddDeviceModelRequestBuilder();
        modelBuilder.setHeaders(new IsyscoreHashMap());
        modelBuilder.setModelName("设备模型" + new Random().nextInt(Short.MAX_VALUE + 1));
        modelBuilder.setProductKey("CM4GNAc08WC");
        TslDetailDomain tsl = new TslDetailDomain();
        List<TslItemDomain> attributes = new ArrayList<>();
        tsl.setAttributes(attributes);
        modelBuilder.setTsl(tsl);

        DataTypeBOOL dataTypeBOOL = new DataTypeBOOL();
        dataTypeBOOL.setTrueValue("开");
        dataTypeBOOL.setFalseValue("关");
        dataTypeBOOL.setType("BOOL");

        TslItemDomain tslItem1 = new TslItemDomain();
        tslItem1.setAccessMode(ReadWriteTypeEnum.R);
        tslItem1.setContent(dataTypeBOOL);
        tslItem1.setDataType("ATTRIBUTE");
        tslItem1.setIdentifier("Status");
        tslItem1.setName("灯状态");
        attributes.add(tslItem1);

        TslItemDomain tslItem2 = new TslItemDomain();
        tslItem2.setAccessMode(ReadWriteTypeEnum.RW);
        tslItem2.setContent(dataTypeBOOL);
        tslItem2.setDataType("ATTRIBUTE");
        tslItem2.setIdentifier("command");
        tslItem2.setName("灯控制");
        attributes.add(tslItem2);

        //创建设备模型
        dmcService.addDeviceModel(modelBuilder);
        return new DemoBaseResult().setData(data);
    }

    private static String devId = "";

    @GetMapping("creatDevice")
    public DemoBaseResult creatDevice() {
        AddDeviceRequestBuilder builder = new AddDeviceRequestBuilder();
        builder.setHeaders(new IsyscoreHashMap());
        builder.setDevId("device" + new Random().nextInt(Short.MAX_VALUE + 1));
        builder.setDevName("设备" + new Random().nextInt(Short.MAX_VALUE + 1));
        builder.setExtra("设备创建测试");
        builder.setGroupId("group0");
        builder.setProductKey("CM4GNAc08WC");
        builder.setSecret("uCuGGnPUbtT745oU");
        AddDeviceResult result = dmcService.addDevice(builder);
        JSONObject resultJson = JSONObject.parseObject(JSONObject.toJSONString(result));
        resultJson.put("message", "您已成功创建设备, 其名称为: " + builder.getDevName() + ", 您可以前往设备集成-设备管理-设备查看该设备");
        DemoBaseResult.Data data = new DemoBaseResult.Data()
                .setParam(JSONObject.parseObject(JSONObject.toJSONString(result.getResponse().getParamMap())))
                .setResult(resultJson);
        devId = builder.getDevId();
        return new DemoBaseResult().setData(data);
    }

    @GetMapping("invokeDeviceService")
    public DemoBaseResult invokeDeviceService() {
        InvokeServiceRequestBuilder builder = new InvokeServiceRequestBuilder();
        builder.setHeaders(new IsyscoreHashMap());
        //TODO 设置参数

        InvokeServiceResult result = dmcService.invokeService(builder);
        JSONObject resultJson = JSONObject.parseObject(JSONObject.toJSONString(result));
        DemoBaseResult.Data data = new DemoBaseResult.Data()
                .setParam(JSONObject.parseObject(JSONObject.toJSONString(result.getResponse().getParamMap())))
                .setResult(resultJson);
        return new DemoBaseResult().setData(data);
    }

    @GetMapping("setAttributeValue")
    public DemoBaseResult setAttributeValue() {
        SetAttributeValueRequestBuilder builder = new SetAttributeValueRequestBuilder();
        builder.setHeaders(new IsyscoreHashMap());
        //TODO 设置参数
        builder.setDevId(devId);
        builder.setIdentifier("command");
        builder.setParam(true);
        SetAttributeValueResult result = dmcService.setAttributeValue(builder);
        JSONObject resultJson = JSONObject.parseObject(JSONObject.toJSONString(result));
        DemoBaseResult.Data data = new DemoBaseResult.Data()
                .setParam(JSONObject.parseObject(JSONObject.toJSONString(result.getResponse().getParamMap())))
                .setResult(resultJson);
        return new DemoBaseResult().setData(data);
    }

    @GetMapping("getAttributeValue")
    public DemoBaseResult getAttributeValue() {
        GetAttributeValueRequestBuilder builder = new GetAttributeValueRequestBuilder();
        builder.setHeaders(new IsyscoreHashMap());
        builder.setDevId(devId);
        builder.setIdentifier("command");
        GetAttributeValueResult result = dmcService.getAttributeValue(builder);
        JSONObject resultJson = JSONObject.parseObject(JSONObject.toJSONString(result));
        DemoBaseResult.Data data = new DemoBaseResult.Data()
                .setParam(JSONObject.parseObject(builder.toJsonString()))
                .setResult(resultJson);
        return new DemoBaseResult().setData(data);
    }

    @GetMapping("getDeviceDetail")
    public DemoBaseResult getDeviceDetail() {
        GetDeviceRequestBuilder builder = new GetDeviceRequestBuilder();
        builder.setHeaders(new IsyscoreHashMap());
        builder.setDevId(devId);
        GetDeviceResult result = dmcService.getDevice(builder);
        JSONObject resultJson = JSONObject.parseObject(JSONObject.toJSONString(result));
        resultJson.put("message", "您已成功获取设备详情");
        DemoBaseResult.Data data = new DemoBaseResult.Data()
                .setParam(JSONObject.parseObject(JSONObject.toJSONString(result.getResponse().getParamMap())))
                .setResult(resultJson);
        return new DemoBaseResult().setData(data);
    }


    @Autowired
    private RpcConnectMapper rpcConnectMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 生成异常信息
     */
    @GetMapping("createErrorForDemo")
    public DemoBaseResult createErrorForDemo() {
        //调用mysql
        rpcConnectMapper.deleteByPrimaryKey(85456789L);
        //调用redis
        stringRedisTemplate.opsForValue().set("USER-ID-00001", "USER-NAME-test", 2, TimeUnit.MINUTES);
        return new DemoBaseResult();
    }


    @IscValue(value = "basic-demo-xyz123.flag")
    private Boolean flag;

    @IscValue(value = "basic-demo-xyz123.mode")
    private String mode;

    @IscValue(value = "basic-demo-xyz123.code")
    private Integer code;

    /**
     * 获取当前动态配置项
     */
    @GetMapping("getDynamicConfig")
    public DemoBaseResult getDynamicConfig() {
        JSONObject resultJson = new JSONObject();
        resultJson.put("message", "您已成功获取动态配置信息");
        JSONObject configJson = new JSONObject();
        configJson.put("flag", flag);
        configJson.put("mode", mode);
        configJson.put("code", code);
        resultJson.put("data", configJson);
        DemoBaseResult.Data data = new DemoBaseResult.Data()
                .setResult(resultJson);
        return new DemoBaseResult().setData(data);
    }


    @Autowired
    private OkHttpClient okHttpClient;

    @Autowired
    private IsyscoreConfigProperties isyscoreConfigProperties;


    /**
     * 应用注册
     * 纯前端
     * 纯后端
     * 桌面菜单应用
     * 后台应用
     * 外联应用
     * 应用卸载
     * 注册应用公私钥
     * 获取accessToken
     */
    @GetMapping("registerFrontApp")
    public DemoBaseResult registerFrontApp() throws Exception {
        RegisterAppDomain appInfo = new RegisterAppDomain();
        appInfo.setCode("basic-demo-register-xyz123");
        appInfo.setName("纯前端应用");
        appInfo.setIntroduction("这是一个纯前端应用的注册demo");
        appInfo.setVersion("v1.0.0.0");
        appInfo.setVersionIntroduction("这是一个初始化版本");
        //状态定义, 注册时启用
        appInfo.setStatus(1);
        //显示菜单定义
        appInfo.setInMenu(1);
        //三方应用定义
        appInfo.setType(3);
        //业务应用定义, 不包含后端服务的应用
        appInfo.setSecondType(5);
        JSONObject extend = new JSONObject();
        extend.put("field", "value");
        appInfo.setExtend(JSONObject.toJSONString(extend));
        RequestBody body = RequestBody.create(JSONObject.toJSONString(appInfo), MediaType.get("application/json; charset=utf-8"));
        Request request = new Request.Builder().url(isyscoreConfigProperties.getRegisterAppUrl() + IsyscoreConstants.REGISTER_APP_URI)
                .post(body)
                .header("isc-tenant-id", "superTenant")
                .header("isc-api-version", "2.1").build();
        okhttp3.Response response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            String bodyString = response.body().string();
            if (!StringUtils.isEmpty(bodyString)) {
                JSONObject resultJson = JSONObject.parseObject(bodyString);
                resultJson.put("message", "您已成功注册应用");
                DemoBaseResult.Data data = new DemoBaseResult.Data()
                        .setParam(JSONObject.parseObject(JSONObject.toJSONString(appInfo)))
                        .setResult(resultJson);
                return new DemoBaseResult().setData(data);
            }
        }
        return new DemoBaseResult();
    }

    @GetMapping("registerBackEndApp")
    public DemoBaseResult registerBackEndApp() throws Exception {
        RegisterAppDomain appInfo = new RegisterAppDomain();
        appInfo.setCode("basic-demo-register-xyz123");
        appInfo.setName("纯后端应用");
        appInfo.setIntroduction("这是一个纯后端应用的注册demo");
        appInfo.setVersion("v1.0.0.0");
        appInfo.setVersionIntroduction("这是一个初始化版本");
        //状态定义, 注册时启用
        appInfo.setStatus(1);
        //不显示菜单定义
        appInfo.setInMenu(2);
        //三方应用定义
        appInfo.setType(3);
        //业务应用定义, 至少包含后端服务的应用
        appInfo.setSecondType(3);
        JSONObject extend = new JSONObject();
        extend.put("field", "value");
        appInfo.setExtend(JSONObject.toJSONString(extend));
        RequestBody body = RequestBody.create(JSONObject.toJSONString(appInfo), MediaType.get("application/json; charset=utf-8"));
        Request request = new Request.Builder().url(isyscoreConfigProperties.getRegisterAppUrl() + IsyscoreConstants.REGISTER_APP_URI)
                .post(body)
                .header("isc-tenant-id", "superTenant")
                .header("isc-api-version", "2.1").build();
        okhttp3.Response response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            String bodyString = response.body().string();
            if (!StringUtils.isEmpty(bodyString)) {
                JSONObject resultJson = JSONObject.parseObject(bodyString);
                resultJson.put("message", "您已成功注册应用");
                DemoBaseResult.Data data = new DemoBaseResult.Data()
                        .setParam(JSONObject.parseObject(JSONObject.toJSONString(appInfo)))
                        .setResult(resultJson);
                return new DemoBaseResult().setData(data);
            }
        }
        return new DemoBaseResult();
    }

    @GetMapping("registerMenuApp")
    public DemoBaseResult registerMenuApp() throws Exception {
        RegisterAppDomain appInfo = new RegisterAppDomain();
        appInfo.setCode("basic-demo-register-xyz123");
        appInfo.setName("桌面菜单应用");
        appInfo.setIntroduction("这是一个桌面菜单应用的注册demo, 顾名思义, 桌面菜单应用是指其入口会出现在桌面, 关键字段是inMenu; " +
                "此处仅是模拟注册, 因为OS应用的运行机制, 该应用的定义是包含后端服务, 需要成功安装完成后, OS才会认可其真实存在性, 才会出现在桌面菜单, 请知悉.");
        appInfo.setVersion("v1.0.0.0");
        appInfo.setVersionIntroduction("这是一个初始化版本");
        //状态定义, 注册时启用
        appInfo.setStatus(1);
        //显示菜单定义
        appInfo.setInMenu(1);
        //三方应用定义
        appInfo.setType(3);
        //业务应用定义, 至少包含后端服务的应用
        appInfo.setSecondType(3);
        //功能菜单接口指定, 接入功能权限所必须
        appInfo.setAclReturnUrl("http://basic-demo-xyz123-service-svc:8857/api/app/basic-demo-xyz123/demo/acl");
        JSONObject extend = new JSONObject();
        extend.put("field", "value");
        appInfo.setExtend(JSONObject.toJSONString(extend));
//        appInfo.setRedirectUrl("https://open.isyscore.com/");
        RequestBody body = RequestBody.create(JSONObject.toJSONString(appInfo), MediaType.get("application/json; charset=utf-8"));
        Request request = new Request.Builder().url(isyscoreConfigProperties.getRegisterAppUrl() + IsyscoreConstants.REGISTER_APP_URI)
                .post(body)
                .header("isc-tenant-id", "superTenant")
                .header("isc-api-version", "2.1").build();
        okhttp3.Response response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            String bodyString = response.body().string();
            if (!StringUtils.isEmpty(bodyString)) {
                JSONObject resultJson = JSONObject.parseObject(bodyString);
                resultJson.put("message", "您已成功注册应用");
                DemoBaseResult.Data data = new DemoBaseResult.Data()
                        .setParam(JSONObject.parseObject(JSONObject.toJSONString(appInfo)))
                        .setResult(resultJson);
                return new DemoBaseResult().setData(data);
            }
        }
        return new DemoBaseResult();
    }

    @GetMapping("registerBackgroundApp")
    public DemoBaseResult registerBackgroundApp() throws Exception {
        RegisterAppDomain appInfo = new RegisterAppDomain();
        appInfo.setCode("basic-demo-register-xyz123");
        appInfo.setName("后台应用");
        appInfo.setIntroduction("这是一个后台应用的注册demo");
        appInfo.setVersion("v1.0.0.0");
        appInfo.setVersionIntroduction("这是一个初始化版本");
        //状态定义, 注册时启用
        appInfo.setStatus(1);
        //不显示菜单定义
        appInfo.setInMenu(2);
        //三方应用定义
        appInfo.setType(3);
        //业务应用定义, 至少包含后端服务的应用
        appInfo.setSecondType(3);
        JSONObject extend = new JSONObject();
        extend.put("field", "value");
        appInfo.setExtend(JSONObject.toJSONString(extend));
        RequestBody body = RequestBody.create(JSONObject.toJSONString(appInfo), MediaType.get("application/json; charset=utf-8"));
        Request request = new Request.Builder().url(isyscoreConfigProperties.getRegisterAppUrl() + IsyscoreConstants.REGISTER_APP_URI)
                .post(body)
                .header("isc-tenant-id", "superTenant")
                .header("isc-api-version", "2.1").build();
        okhttp3.Response response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            String bodyString = response.body().string();
            if (!StringUtils.isEmpty(bodyString)) {
                JSONObject resultJson = JSONObject.parseObject(bodyString);
                resultJson.put("message", "您已成功注册应用");
                DemoBaseResult.Data data = new DemoBaseResult.Data()
                        .setParam(JSONObject.parseObject(JSONObject.toJSONString(appInfo)))
                        .setResult(resultJson);
                return new DemoBaseResult().setData(data);
            }
        }
        return new DemoBaseResult();
    }

    @GetMapping("registerOutApp")
    public DemoBaseResult registerOutApp() throws Exception {
        RegisterAppDomain appInfo = new RegisterAppDomain();
        appInfo.setCode("basic-demo-register-xyz123");
        appInfo.setName("外联应用");
        appInfo.setIntroduction("这是一个外联应用的注册demo, 外联应用不归OS管理, 仅在桌面菜单提供应用入口");
        appInfo.setVersion("v1.0.0.0");
        appInfo.setVersionIntroduction("这是一个初始化版本");
        //状态定义, 注册时启用
        appInfo.setStatus(1);
        //显示菜单定义
        appInfo.setInMenu(1);
        //外联应用定义
        appInfo.setType(5);
        //业务应用定义, 不包含后端服务的应用
        appInfo.setSecondType(5);
        JSONObject extend = new JSONObject();
        extend.put("field", "value");
        appInfo.setExtend(JSONObject.toJSONString(extend));
        //定义跳转路径
        appInfo.setRedirectUrl("https://open.isyscore.com/");
        RequestBody body = RequestBody.create(JSONObject.toJSONString(appInfo), MediaType.get("application/json; charset=utf-8"));
        Request request = new Request.Builder().url(isyscoreConfigProperties.getRegisterAppUrl() + IsyscoreConstants.REGISTER_APP_URI)
                .post(body)
                .header("isc-tenant-id", "superTenant")
                .header("isc-api-version", "2.1").build();
        okhttp3.Response response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            String bodyString = response.body().string();
            if (!StringUtils.isEmpty(bodyString)) {
                JSONObject resultJson = JSONObject.parseObject(bodyString);
                resultJson.put("message", "您已成功注册应用");
                DemoBaseResult.Data data = new DemoBaseResult.Data()
                        .setParam(JSONObject.parseObject(JSONObject.toJSONString(appInfo)))
                        .setResult(resultJson);
                return new DemoBaseResult().setData(data);
            }
        }
        return new DemoBaseResult();
    }

    @GetMapping("registerLightApp")
    public DemoBaseResult registerLightApp() throws Exception {
        RegisterAppDomain appInfo = new RegisterAppDomain();
        appInfo.setCode("basic-demo-register-xyz123");
        appInfo.setName("轻应用");
        appInfo.setIntroduction("这是一个轻应用的注册demo");
        appInfo.setVersion("v1.0.0.0");
        appInfo.setVersionIntroduction("这是一个初始化版本");
        //状态定义, 注册时启用
        appInfo.setStatus(1);
        //显示菜单定义
        appInfo.setInMenu(1);
        //轻应用定义
        appInfo.setType(6);
        //业务应用定义, 不包含后端服务的应用
        appInfo.setSecondType(5);
        JSONObject extend = new JSONObject();
        extend.put("field", "value");
        appInfo.setExtend(JSONObject.toJSONString(extend));
        //定义跳转路径
        appInfo.setRedirectUrl("https://open.isyscore.com/");
        RequestBody body = RequestBody.create(JSONObject.toJSONString(appInfo), MediaType.get("application/json; charset=utf-8"));
        Request request = new Request.Builder().url(isyscoreConfigProperties.getRegisterAppUrl() + IsyscoreConstants.REGISTER_APP_URI)
                .post(body)
                .header("isc-tenant-id", "superTenant")
                .header("isc-api-version", "2.1").build();
        okhttp3.Response response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            String bodyString = response.body().string();
            if (!StringUtils.isEmpty(bodyString)) {
                JSONObject resultJson = JSONObject.parseObject(bodyString);
                resultJson.put("message", "您已成功注册应用");
                DemoBaseResult.Data data = new DemoBaseResult.Data()
                        .setParam(JSONObject.parseObject(JSONObject.toJSONString(appInfo)))
                        .setResult(resultJson);
                return new DemoBaseResult().setData(data);
            }
        }
        return new DemoBaseResult();
    }

    @GetMapping("deleteApp")
    public DemoBaseResult deleteApp() throws Exception {
        // 清理demo应用
        Request request = new Request.Builder().url(isyscoreConfigProperties.getRegisterAppUrl() + "/api/rc-application/application/delete?code=basic-demo-register-xyz123")
                .delete()
                .header("isc-tenant-id", "superTenant")
                .header("token", TokenUtils.getLoginToken())
                .header("isc-api-version", "2.1").build();
        okhttp3.Response response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            String body = response.body().string();
            if (!StringUtils.isEmpty(body)) {
                JSONObject resultJson = JSONObject.parseObject(body);
                resultJson.put("message", "您已成功删除应用");
                DemoBaseResult.Data data = new DemoBaseResult.Data()
                        .setResult(resultJson);
                return new DemoBaseResult().setData(data);
            }
        }
        return new DemoBaseResult();
    }

    /**
     * 公钥字符串
     */
    private static String publicKey = "";

    @GetMapping("registerAppKey")
    public DemoBaseResult registerAppKey() throws Exception {
        RegisterAppKeyReq registerAppKeyReq = new RegisterAppKeyReq();
        registerAppKeyReq.setAppCode("basic-demo-xyz123");
        registerAppKeyReq.setPermission(new ArrayList<>());
        RequestBody body = RequestBody.create(JSONObject.toJSONString(registerAppKeyReq), MediaType.get("application/json; charset=utf-8"));
        Request request = new Request.Builder().url(isyscoreConfigProperties.getRegisterAppUrl() + "/api/app/operation-center/monitoring/dev/param/registerAppKey")
                .post(body)
                .header("token", token)
                .build();
        okhttp3.Response response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            String bodyString = response.body().string();
            if (!StringUtils.isEmpty(bodyString)) {
                JSONObject resultJson = JSONObject.parseObject(bodyString);
                resultJson.put("message", "您已成功公私钥");
                publicKey = resultJson.getString("data");
                DemoBaseResult.Data data = new DemoBaseResult.Data()
                        .setParam(JSONObject.parseObject(JSONObject.toJSONString(registerAppKeyReq)))
                        .setResult(resultJson);
                return new DemoBaseResult().setData(data);
            }
        }
        return new DemoBaseResult();
    }

    @GetMapping("getAccessToken")
    public DemoBaseResult getAccessToken() throws Exception {
        Map<String, String> param = new HashMap<>(8);
        param.put("publicKey", publicKey);
        RequestBody body = RequestBody.create(JSONObject.toJSONString(param), MediaType.get("application/json; charset=utf-8"));
        Request request = new Request.Builder().url(isyscoreConfigProperties.getRegisterAppUrl() + "/api/core/authorization/auth/accessToken")
                .post(body)
                .header("token", token)
                .build();
        okhttp3.Response response = okHttpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            String bodyString = response.body().string();
            if (!StringUtils.isEmpty(bodyString)) {
                JSONObject resultJson = JSONObject.parseObject(bodyString);
                resultJson.put("message", "您已成功获取访问令牌");
                DemoBaseResult.Data data = new DemoBaseResult.Data()
                        .setParam(JSONObject.parseObject(JSONObject.toJSONString(param)))
                        .setResult(resultJson);
                return new DemoBaseResult().setData(data);
            }
        }
        return new DemoBaseResult();
    }


}
